import { getMenuList } from "@/api";
import type { Menu } from "@/typings";
import { getAllBreadcrumbList, getFlatMenuList } from "@/utils";
import { useRouter } from "vue-router";
import { defineStore } from "pinia";
import { ref } from "vue";

const key: string = "useAuthStore";

export const useAuthStore = defineStore(key, () => {
  /**
   * @description 用户菜单
   */
  const userMenu = ref<Menu[]>([]);
  const router = useRouter();

  /**
   * @description 获取菜单
   */
  const getAuthMenuList = async () => {
    try {
      const menuList = await getMenuList();
      userMenu.value = menuList.data;
    } catch (error) {
      console.error("获取菜单失败");
    }
  };

  /**
   * @description 获取面包屑
   * @returns {Object}
   */
  function breadcrumbListGet(): { [key: string]: any } {
    const staticRoute = router.options.routes.find((item) => item.path === "/layout");
    return getAllBreadcrumbList([...(staticRoute?.children as Array<any>), ...userMenu.value]);
  }

  /**
   * @description 获取扁平化菜单
   * @returns {Menu[]}
   */
  function flatMenuListGet(): Menu[] {
    return getFlatMenuList(userMenu.value);
  }

  return {
    userMenu,
    getAuthMenuList,
    breadcrumbListGet,
    flatMenuListGet
  };
});
